package com.cuixichang.minimalism.core.security.utils;

import cn.hutool.core.bean.BeanUtil;
import com.cuixichang.minimalism.basal.core.BaseDTO;
import com.cuixichang.minimalism.core.security.userdetails.CredentialDetail;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.*;

public class SecurityBeanUtil {

    public static CredentialDetail getCredentialDetail(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof AnonymousAuthenticationToken){
            return null;
        }else {
            CredentialDetail principal = (CredentialDetail) authentication.getPrincipal();
            if(Objects.nonNull(principal)){
                return principal;
            }else {
                return null;
            }
        }
    }

    public static <DTO extends BaseDTO,Request> DTO request2dto(Request request,Class<DTO> dtoClass){
        DTO dto = BeanUtil.toBean(request, dtoClass);
        if(Objects.nonNull(dto)){
            CredentialDetail principal = getCredentialDetail();
            if(Objects.nonNull(principal)){
                dto.setCreateLoginId(principal.getLoginId());
            }
        }
        return dto;
    }
}
